<?php
    // +----------------------------------------------------------------------
    // | Created by PHPstorm: JRKAdmin框架 [ JRKAdmin ]
    // +----------------------------------------------------------------------
    // | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
    // +----------------------------------------------------------------------
    // | SiteUrl: http://www.luckyhhy.cn
    // +----------------------------------------------------------------------
    // | Author: LuckyHhy <jackhhy520@qq.com>
    // +----------------------------------------------------------------------
    // | Date: 2019/11/14 15:04
    // +----------------------------------------------------------------------
    // | Description:  
    // +----------------------------------------------------------------------

    namespace app\admin\controller;

    use app\admin\behavior\LoginRecord;
    use app\admin\model\AdminUser;
    use app\common\service\LoginService;
    use Jrk\Util;
    use think\Controller;
    use think\Db;
    use think\Exception;
    use think\facade\Cookie;
    use think\facade\Session;
    use think\Request;

    class Login extends Controller
    {



        /**
         * @return mixed|\think\response\Redirect
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/1/16
         * @name: index
         * @describe:登录页面
         */
        public function index()
        {
            if(LoginService::getAdminUserInfo()) { //已经登录
                return redirect('/admin/index/index');
            }
            else {
                $user=[];
                $user['username']='';
                $user['pass']='';
                if(LoginService::getRemember()) { //有记录cookie
                    $token = LoginService::getRemember();
                    $info=Db::name("admin_user")->where("tokens",$token)->find();
                    if ($info){
                        $user['username']=$info['username'];
                        $user['pass']=Util::think_decrypt($info['password']);
                    }
                }
                $this->assign('user',$user);

                return $this->fetch();
            }

        }


        /**
         * @param Request $request
         * @param AdminUser $user
         * @return mixed
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @name: login_check
         * @describe:登录检测
         */
        public function login_check(Request $request,AdminUser $user)
        {
            if($request->isPost()) {
                $data  = $request->only(['username', 'password', '__token__','remember']);
                try {

                    $users =$user->where('username', $data['username'])->find();
                    if(!empty($users)) {

                        if($users['password']!= Util::think_encrypt($data["password"])){
                            $this->error('用户密码错误');
                        }

                        //保存用户信息
                        LoginService::storeAdminInfo($users);

                        Session::set("admin_id",$users['id']); //ID
                        Session::set("admin_name",$users['username']); //ID
                        Session::set("admin_role_id",$users['role_id']);//角色ID

                        //记录用户登录状态
                        $tokens=$this->makeToken();//生成随机数
                        LoginService::adminRemember($tokens);
                        $user->where("id",$users['id'])->setField('cookie',$tokens);//更新token值

                        //记住用户登录账号密码
                         if(isset($data['remember'])) {
                              $token=$this->makeToken();//生成随机数
                              $ok=$user->where("id",$users['id'])->setField('tokens',$token);//更新token值
                              if ($ok){
                                  LoginService::adminRemember($token); //记住登录用户信息
                              }
                          }

                         //记录登录日志
                        addLog("login","用户登录");

                        //记录访问者IP
                        $this->recod();

                        unset($users['tokens']);

                        hooks(LoginRecord::class,['user'=>$users->toArray()]); //登录数据修改

                        $this->success("登录成功");
                    }
                    else {
                        $this->error('该用户不存在');
                    }
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }

            }
        }


        /**
         * @return string
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @name: makeToken
         * @describe:生成一个不会重复的字符串
         */
        public function makeToken()
        {
            $str = md5(uniqid(md5(microtime(true)), true)); //
            $str = sha1($str); //加密
            return $str;
        }

        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/2/28
         * @name: recod
         * @describe:记录访问者IP
         */
        public function recod(){
            try{
                $ip=Util::get_client_ip();
                $dz=Util::getAddress($ip);
                $dizhi='';
                if (!empty($dz)){
                    $dizhi=$dz['content']['address_detail']['province'].$dz['content']['address_detail']['city'];
                }
                $data=[
                    'ip'=>$ip,
                    'address'=>$dizhi,
                    'create_time'=>time(),
                    'browser'=>Util::getBrowser()
                ];

                Db::name("recod")->insert($data);
            }catch (Exception $exception){
                \think\facade\Log::error($exception->getMessage());
                $this->error($exception->getMessage());
            }
        }



        /**
         * @return \think\response\Redirect
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @name: login_out
         * @describe:退出登录
         */
        public function login_out()
        {
            Cookie::delete("jrkhhy");
            $ok=LoginService::loginOut();
            if ($ok){
                return  redirect('/admin/login/index')->with('success', '退出登录');
            }else{
                \think\facade\Log::error("退出登录失败");
                redirect('/admin/login/index')->with('success', '退出登录');
            }
        }



    }